//
//  GroupChatVC.m
//  SelfDriving
//
//  Created by apple on 16/3/29.
//  Copyright © 2016年 apple. All rights reserved.
//
#import "GroupChatVC.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "AddMapViewController.h"
#import "UIImage+Rotate_Flip.h"
#import "UIImage+Resize.h"
#import "ImageProgressQueue.h"

#import "TalkingRecordView.h"
#import "AudioMsgPlayer.h"
#import "GroupDetails.h"
#import "AddHongbaoView.h"
#import "HongbaoViewController.h"
#import "BusinessService+User.h"
#import "PositionViewController.h"
#import "MapViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
#import "AddFileViewController.h"
#import "EmotionInputView.h"

@interface GroupChatVC ()<UITableViewDelegate,UITableViewDataSource,AddMapViewControllerDatalete,KYExpressionInputViewDelegate,UITextViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,AddHongbaoViewDeteage,ImageProgressDelagete,TCResultGroupDelegate,MLEmojiLabelDelegate,PositionViewControllerDelete,GroupDetailsDelete,AddFileVCDelegate,EmotionInputViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *changeButton;
@property (weak, nonatomic) IBOutlet UIView *gxview;
@property (weak, nonatomic) IBOutlet UIView *bview;
@property (weak, nonatomic) IBOutlet UIButton *sender_btn;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UITextView *content_Text;
@property (weak, nonatomic) IBOutlet UIView *bgview;
@property (nonatomic, assign) id        subPageDelegate;
@property (weak, nonatomic) IBOutlet UIButton *gongju;
@property (weak, nonatomic) IBOutlet UIImageView *bgimg;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) ZFPlayerControlView *contrlView;
@property (nonatomic, strong) AddFileViewController *addFileVC;
@property (nonatomic, assign) BOOL isVideo; //xhw2018-1-29加:是否要隐藏addfileVC添加视频板块
@property (nonatomic, strong) EmotionInputView *emojiView;
@property (nonatomic, strong) UIView *toolbar;

@end

@implementation GroupChatVC{
    AVPlayer *_players;
    NSMutableDictionary *addres;
    
    NSMutableArray *resultArray;
    BOOL isshow;
    int keyboardhight;
    NSString *touid;
    NSString *talk_id;
    int istablescoolr;//进入第一次滑动到底部
    BOOL isUp;
    KYExpressionInputView *inputView;
    int  rh;
    int h;
    TalkingRecordView*      recordView;
    LoginResponseModel *gxuser;
    NSMutableString *headimgs;//群头像
    NSString *sid;
    UIImage *sendImage;
}
#pragma mrak 获取头像
-(void)gethead{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:sid forKey:@"sessionid"];
    [[BusinessService shareInstance]detail:dic success:^(id result) {
        LoginResponseModel *user = result;
        if([user isKindOfClass:[LoginResponseModel class]]){
            for (NSMutableDictionary *img  in user.list) {
                [headimgs appendFormat:@"%@,",[img objectForKey:@"headlarge"]];
            }
        }
    } failure:^(id result) {
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    //     [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    
    headimgs = [NSMutableString string];
    if (self.tcs) {
        
        resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:self.tcs.ID typeChat:forChatTypeRoom sinceRowID:0 maxRowID:0 count:0 page:0];
//        NSLog(@"GroupChatVC->viewWillAppear->%@",self.tcs.ID);
        [[ThinkChat instance]hasReadSessionID:self.tcs.ID typeChat:forChatTypeRoom];
        sid = self.tcs.ID;
    }else{
        [[ThinkChat instance] getConversationDetail:self.model.ID delegate:self];
        
        resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:self.model.ID typeChat:forChatTypeRoom sinceRowID:0 maxRowID:0 count:0 page:0];
        [[ThinkChat instance]hasReadSessionID:self.model.ID typeChat:forChatTypeRoom];
        sid = _model.ID;
    }
    NSLog(@"xhw->GroupChatVC->viewWillAppear->sessionID:%@",sid);

    NSLog(@"xhw->GroupChatVC->viewWillAppear->resultArray.count:%lu",(unsigned long)resultArray.count);
    [self gethead];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:sid forKey:@"sessionid"];
    [[BusinessService shareInstance]detail:dic success:^(id result) {
        LoginResponseModel * user = result;
        if ([user isKindOfClass:[LoginResponseModel class]]) {
            self.navigationItem.title = user.name;
        }
    } failure:^(id result) {
        
    }];
    
    
    
    [[AppDelegate shareDelegate]showMsgCount];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearSession:) name:@"clearSession" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initGroupList:) name:@"groupList" object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(psend:)
     name:@"psendg"
     object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(pzsend:)
     name:@"pzsendg"
     object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(endQgx:)
     name:@"endQgxG"
     object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(initQgx:)
     name:@"initQgxG"
     object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gongxiangzhongzhi:) name:@"gongxiangzhongzhig" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearSession:) name:@"clearSessionGroup" object:nil];//xhw2018-2-5加
    
    [_table reloadData]; //xhw2018-1-26加
}
-(void)gongxiangzhongzhi:(NSNotification *)not{
    _gxview.hidden = YES;
}
#pragma mark - TCResultGroupDelegate
- (void)tcResultGroup:(TCGroup *)itemG error:(TCError *)itemE {
    if (!itemE) {
        self.navigationItem.title = [NSString stringWithFormat:@"%@",itemG.name];
        if (itemG.name==nil) {
            if (self.tcs) {
                self.navigationItem.title = [NSString stringWithFormat:@"%@",self.tcs.name];
            }else{
                self.navigationItem.title = [NSString stringWithFormat:@"%@",self.model.name];
            }
        }
    }
}

- (void)dealloc {
    NSLog(@"GroupChatVC->initGroupList->dealloc");
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    resultArray = [NSMutableArray array];
    _gongju.layer.cornerRadius = 4;
    CGRect f = _bview.frame;
    f.origin.y = SCRE_HEIGHT - f.size.height + 100;
    _bview.frame = f;
    
    CGRect t = _table.frame;
    t.size.height = f.origin.y-50;
    _table.frame = t;
    
    _content_Text.delegate = self;
    
    _content_Text.layer.cornerRadius = 5;
    _content_Text.layer.borderColor = colorBG.CGColor;
    _content_Text.layer.borderWidth = 0.5;
    
    self.navigationController.navigationBarHidden = NO;
    UIApplication *app = [UIApplication sharedApplication];
    // 应用程序右上角数字
    int unReadCount = [[ThinkChat instance] getUnReadMessageCount];
    app.applicationIconBadgeNumber = unReadCount;
    
    
    _sender_btn.layer.cornerRadius = 5;
    _sender_btn.layer.borderColor = colorBG.CGColor;
    //    _sender_btn.layer.borderColor = UIColorRed.CGColor;
    _sender_btn.layer.borderWidth = 0.5;
    
    _sender_btn.backgroundColor = [UIColor clearColor];
    _sender_btn.frame = self.content_Text.frame;
    [_sender_btn.superview bringSubviewToFront:_sender_btn];
    [_sender_btn setTitle:@"按住 说话" forState:UIControlStateNormal];
    [_sender_btn setBackgroundColor:colorBG forState:UIControlStateNormal];
    [_sender_btn addTarget:self action:@selector(button1BackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
    [_sender_btn addTarget:self action:@selector(button1BackGroundNormal:) forControlEvents:UIControlEventTouchUpInside];
    
    [_sender_btn setTitleColor:UIColorBlack forState:UIControlStateNormal];
    
    _sender_btn.hidden = YES;

    //后面加的
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];
    [_table addGestureRecognizer:tap];
    //语音
       recordView = [[TalkingRecordView alloc] initWithFrame:CGRectMake(self.view.width/2-80, (self.view.height-160)/2, 160, 160) del:self];
    [self.view addSubview:recordView];
    recordView.hidden = YES;
    
    
}
-(void)initGroupList:(NSNotification *)sender{
    NSLog(@"xhw->GroupChatVC->initGroupList->self.tcs.ID%@",self.tcs.ID);
    TCMessage * msg = sender.object;
    if (msg.typeChat == forChatTypeRoom && [msg.withID isEqualToString:_tcs.ID]) {
        
        resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:self.tcs.ID typeChat:forChatTypeRoom sinceRowID:0 maxRowID:0 count:0 page:0];
        [[ThinkChat instance]hasReadSessionID:self.tcs.ID typeChat:forChatTypeRoom];
        
        [_table reloadData];
        [self scrollToBottom];
    }else{
        resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:self.model.ID typeChat:forChatTypeRoom sinceRowID:0 maxRowID:0 count:0 page:0]; //xhw2018-1-26改:获取聊天列表是传self.model.ID(之前是传的self.tsc.ID,因为在发起会话时，这里的tcs没有传值，传的model)
        [[ThinkChat instance]hasReadSessionID:self.tcs.ID typeChat:forChatTypeRoom];
//        [_table reloadData];
        [self scrollToBottom];
    }
    NSLog(@"xhw->GroupChatVC->initGroupList->resultArray.count%lu",(unsigned long)resultArray.count);
}
- (void)clearSession:(NSNotification*)sender {
//    TCSession* itemS = sender.object;
//    for (TCSession* tmpS in resultArray) {
//
//        if (tmpS.typeChat == itemS.typeChat && [tmpS.ID isEqualToString:itemS.ID]) {
//            [resultArray removeObject:tmpS];
//            [_table reloadData];
//            break;
//        }
//    }
    
}


//泡泡文本
- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf withPosition:(int)position{
    
    //计算大小
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    NSLog(@"%f,%f",size.width,size.height);
    
    
    //添加文本信息
    UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?15.0f:22.0f, 20.0f, size.width+10, size.height+10)];
    bubbleText.backgroundColor = [UIColor clearColor];
    bubbleText.font = font;
    bubbleText.numberOfLines = 0;
    bubbleText.lineBreakMode = NSLineBreakByWordWrapping;
    bubbleText.text = text;
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    return returnView;
}

//泡泡文本
- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf withPosition:(int)position indexPath:(NSIndexPath *)indexPath{
    
    //计算大小
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    MLEmojiLabel *bubbleText = [[MLEmojiLabel alloc]initWithFrame:CGRectMake(fromSelf?15.0f:22.0f,10, size.width+10, size.height+10)];
    bubbleText.lineBreakMode = NSLineBreakByCharWrapping;
    bubbleText.isNeedAtAndPoundSign = YES;
    bubbleText.numberOfLines = 0;
    bubbleText.disableEmoji = NO;
    bubbleText.disableThreeCommon = NO;
    bubbleText.delegate = self;
    
    [ValidateHelper ReplaceMLEmojiLabel:text emojilable:bubbleText];
    [bubbleText sizeToFit];
    CGRect backFrame = bubbleText.frame;
    backFrame.size.height += 13+13+5;
    bubbleText.frame = backFrame;
    rh = backFrame.size.height;
    //    [_table reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+10.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+10.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    return returnView;
}
-(void)mlEmojiLabel:(MLEmojiLabel *)emojiLabel didSelectLink:(NSString *)link withType:(MLEmojiLabelLinkType)type{
    SVWebViewController *webC = [[SVWebViewController alloc] initWithAddress:link];
    webC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webC animated:YES];
    
}

#pragma mark  共享位置
- (UIView *)GXweizhiView:(TCMessage *)model from:(BOOL)fromSelf withIndexRow:(NSInteger)indexRow  withPosition:(int)position{
    
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    
    bubble = [bubble imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    bubbleImageView.tintColor = [UIColor whiteColor];
    
    bubble = [ImageService imageWithColor:UIColorFromRGB(0x55DF6B) img:bubble];
    
    
    //添加文本信息
    UIView *bubbleText = [[UIView alloc] initWithFrame:CGRectMake(fromSelf?10.0f:10, 20.0f, 100, 30)];
    
    //    //位置信息标题
    //    UILabel *htext = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?70:-10,-10, 320-210, 50)];
    //    htext.backgroundColor = [UIColor clearColor];
    //    htext.numberOfLines = 0;
    //    if (!fromSelf) {
    //        htext.textAlignment = NSTextAlignmentRight;
    //    }
    //    htext.lineBreakMode = NSLineBreakByWordWrapping;
    //    htext.text = @"位置分享";
    //    htext.font = [UIFont systemFontOfSize:15];
    //    //    htext.textColor = [UIColor whiteColor];
    //    [bubbleText addSubview:htext];
    
    NSMutableDictionary *dic = model.extDic;
    NSString *con = fromSelf?@"我共享了位置":[NSString stringWithFormat:@"%@共享了位置",[dic objectForKey:@"nickname"]];
    CGSize s =[ValidateHelper sizeOfText:con theFont:[UIFont systemFontOfSize:14]];
    
    //位置信息内容
    UILabel *dizhi = [[UILabel alloc] initWithFrame:CGRectMake(25,0,fromSelf?s.width+20:s.width+10, 30)];
    CGRect f  = bubbleText.frame;
    f.size.width = dizhi.frame.size.width;
    bubbleText.frame = f;
    
    dizhi.backgroundColor = [UIColor clearColor];
    dizhi.numberOfLines = 0;
    //    if (!fromSelf) {
    //        dizhi.textAlignment = NSTextAlignmentRight;
    //    }
    
    dizhi.lineBreakMode = NSLineBreakByWordWrapping;
    dizhi.text = con;
    dizhi.font = [UIFont systemFontOfSize:13];
    //    dizhi.textColor = [UIColor whiteColor];
    [bubbleText addSubview:dizhi];
    
    UIImageView *himg = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 15, 20)];
    himg.image = [UIImage imageNamed:@"ltgxtb"];
    [bubbleText addSubview:himg];
    
    
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+40);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    //绑定事件
    BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH-140, 30)];
    [btn addTarget:self action:@selector(togongxiang:) forControlEvents:UIControlEventTouchUpInside];
    btn.dic = dic;
    [bubbleText addSubview:btn];
    return returnView;
}

#pragma mark 语音显示
- (UIView *)yuyinView:(TCMessage *)model from:(BOOL)fromSelf withIndexRow:(NSInteger)indexRow  withPosition:(int)position{
    
    
    TCVoiceMessageBody *body = (TCVoiceMessageBody *)model.body;
    //根据语音长度
    int yuyinwidth = 66+body.voiceTime;
    
    BaseButton *button = [BaseButton buttonWithType:UIButtonTypeCustom];
    button.tag = indexRow;
    button.model = model;
    if(fromSelf)
        button.frame =CGRectMake(SCRE_WIDTH-position-yuyinwidth, 15, yuyinwidth, 54);
    else
        button.frame =CGRectMake(position, 15, yuyinwidth, 54);
    
    //image偏移量
    UIEdgeInsets imageInsert;
    imageInsert.top = -10;
    imageInsert.left = fromSelf?button.frame.size.width/3:-button.frame.size.width/3;
    button.imageEdgeInsets = imageInsert;
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(yuyinwidth - 40, fromSelf?45/2-10:45/2, 20, 20)];
    img.image =  [UIImage imageNamed:fromSelf?@"SenderVoiceNodePlaying":@"ReceiverVoiceNodePlaying"];
    [ImageService imageWithColor:[UIColor whiteColor] img:img.image];
    
    [button addSubview:img];
    UIImage *backgroundImage = [UIImage imageNamed:fromSelf?@"lthb_y":@"lthb_z"];
    backgroundImage = [backgroundImage stretchableImageWithLeftCapWidth:20 topCapHeight:0];
    backgroundImage = [ImageService imageWithColor:UIColorFromRGB(0x59DC65)  img:backgroundImage];
    [button setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(fromSelf?-30:button.frame.size.width, 0, 30, button.frame.size.height)];
    label.text = [NSString stringWithFormat:@"%.1lf''",body.voiceTime];
    label.textColor = [UIColor grayColor];
    label.font = [UIFont systemFontOfSize:13];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    [button addSubview:label];
    [button addTarget:self action:@selector(bofang:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

//图片
- (UIView *)tupianView:(TCMessage *)model from:(BOOL)fromSelf cell:(UITableViewCell*)cell withIndexRow:(NSInteger)indexRow  withPosition:(int)position{
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    bubble = [bubble imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    bubbleImageView.tintColor = [UIColor whiteColor];
    
    TCImageMessageBody *imag = (TCImageMessageBody *)model.body;
    
    //图片
    UIImageView *bubbleText = [[UIImageView alloc] initWithFrame:CGRectMake(fromSelf?10.0f:15, fromSelf?20.0f:20,imag.imgWidth, imag.imgHeight)];
    bubbleText.layer.cornerRadius = 4;
    bubbleText.clipsToBounds = YES;
    bubbleText.image = [UIImage imageNamed:@"notimgs"];
    ImageProgress * pro = [[ImageProgress alloc] initWithUrl:imag.imgUrlL delegate:self];
    if (!pro.loaded) {
        [pro startDownload];
    }else{
        bubbleText.image = pro.image;
    }
    pro.tag = indexRow*10;
    bubbleText.tag = indexRow;
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+25.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    //绑定事件
    BaseButton *btn = [[BaseButton alloc]initWithFrame:bubbleText.frame];
    btn.tag = indexRow;
    [btn addTarget:self action:@selector(picenlarge:) forControlEvents:UIControlEventTouchUpInside];
    [returnView addSubview:btn];
    
    return returnView;
    
}
#pragma mark 图片加载回调
-(void)imageProgress:(ImageProgress *)sender completed:(BOOL)bl{
    if (bl) {
        if (sender.tag == 0) {
            if (sender.image!=nil) {
                NSMutableArray  *imgdata = [[NSMutableArray alloc]init];
                ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc] init];
                
                photo.photoImage = sender.image;
                
                [imgdata addObject:photo];
                // 图片游览器
                ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc] init];
                // 数据源/delegate
                //    pickerBrowser.delegate = self;
                pickerBrowser.status = UIViewAnimationAnimationStatusFade;
                
                // 数据源可以不传，传photos数组 photos<里面是ZLPhotoPickerBrowserPhoto>
                pickerBrowser.photos = imgdata;
                // 是否可以删除照片
                pickerBrowser.editing = NO;
                // 当前选中的值
                pickerBrowser.currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                // 展示控制器
                [pickerBrowser showPickerVc:self];
            }
        }else{
            if (sender.image!=nil) {
                UIImageView  *img = (UIImageView *)[_table viewWithTag:sender.tag/10];
                img.image = sender.image;
            }
        }
    }
}

//红包
- (UIView *)hongbaoView:(TCMessage *)model from:(BOOL)fromSelf withIndexRow:(NSInteger)indexRow  withPosition:(int)position{
    
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"lthb_y":@"lthb_z" ofType:@"png"]];
    
    bubble = [bubble imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    bubbleImageView.tintColor = UIColorFromRGB(0xE7912E);
    NSMutableDictionary *dic = model.extDic;
    
    CGSize s =[ValidateHelper sizeOfText:[dic objectForKey:@"title"] theFont:[UIFont systemFontOfSize:14]];
    s.width = s.width<50?s.width+50:s.width;
    
    //添加文本信息
    UIView *bubbleText = [[UIView alloc] initWithFrame:CGRectMake(fromSelf?10:22.0f, 20.0f,s.width+50, 55)];
    
    
    //添加红包文本信息
    UILabel *htext = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?60:0, fromSelf?5:10, s.width, 50)];
    htext.backgroundColor = [UIColor clearColor];
    htext.numberOfLines = 0;
    htext.lineBreakMode = NSLineBreakByWordWrapping;
    htext.text = [NSString stringWithFormat:@"%@\n%@",[dic objectForKey:@"title"],@"查看红包"];
    htext.font = [UIFont systemFontOfSize:13];
    htext.textColor = [UIColor whiteColor];
    [bubbleText addSubview:htext];
    UIImageView *himg = [[UIImageView alloc] initWithFrame:CGRectMake(fromSelf?10:s.width, fromSelf?5:10, 40, 50)];
    himg.image = [UIImage imageNamed:@"lthb"];
    [bubbleText addSubview:himg];
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    //绑定事件
    BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH-140, 70)];
    [btn addTarget:self action:@selector(hongbao:) forControlEvents:UIControlEventTouchUpInside];
    btn.dic = dic;
    [bubbleText addSubview:btn];
    
    
    return returnView;
    
    
}
//位置分享
- (UIView *)weizhiView:(TCMessage *)model from:(BOOL)fromSelf withIndexRow:(NSInteger)indexRow  withPosition:(int)position{
    
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
//    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"lthb_y":@"lthb_z" ofType:@"png"]];
//
//    bubble = [bubble imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
//    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
//    bubbleImageView.tintColor = [UIColor whiteColor];
//
//
//
//    //添加文本信息
//    UIView *bubbleText = [[UIView alloc] initWithFrame:CGRectMake(fromSelf?10.0f:22.0f, 20.0f, SCRE_WIDTH-140, 70)];
//
//
//
//    //位置信息标题
//    UILabel *htext = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?70:22.0f, -10, SCRE_WIDTH-210, 50)];
//    htext.backgroundColor = [UIColor clearColor];
//    htext.numberOfLines = 0;
//    htext.lineBreakMode = NSLineBreakByWordWrapping;
//    htext.text = @"位置分享";
//    htext.font = [UIFont systemFontOfSize:15];
//    //    htext.textColor = [UIColor whiteColor];
//    [bubbleText addSubview:htext];
//
//    TCLocationMessageBody *lmodel  = (TCLocationMessageBody *)model.body;
//
//    //位置信息内容
//    UILabel *dizhi = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?70:22.0f,20, SCRE_WIDTH-210, 50)];
//    dizhi.backgroundColor = [UIColor clearColor];
//    dizhi.numberOfLines = 0;
//    dizhi.lineBreakMode = NSLineBreakByWordWrapping;
//    dizhi.text = lmodel.address;
//    dizhi.font = [UIFont systemFontOfSize:13];
//    //    dizhi.textColor = [UIColor whiteColor];
//    [bubbleText addSubview:dizhi];
//
//    UIImageView *himg = [[UIImageView alloc] initWithFrame:CGRectMake(fromSelf?5:60, 5, 60, 60)];
//    himg.image = [UIImage imageNamed:@"ltdili"];
//    [bubbleText addSubview:himg];
//
//
//
//    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
//
//    if(fromSelf)
//        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
//    else
//        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
//
//    [returnView addSubview:bubbleImageView];
//    [returnView addSubview:bubbleText];
//
//    //绑定事件
//    BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH-140, 70)];
//    btn.model = lmodel;
//    [btn addTarget:self action:@selector(address:) forControlEvents:UIControlEventTouchUpInside];
//    [bubbleText addSubview:btn];
//
//    return returnView;
    
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    bubble = [bubble imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    bubbleImageView.tintColor = [UIColor whiteColor];
    
    
    
    //添加文本信息
    UIView *bubbleText = [[UIView alloc] initWithFrame:CGRectMake(fromSelf?10.0f:22.0f, 20.0f, 320-140, 70)];
    //    UIView *bubbleText = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 20.0f, 320-140, 70)];
    
    //位置信息标题
    UILabel *htext = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?70:-10,-10, 320-210, 50)];
    //    UILabel *htext = [[UILabel alloc] initWithFrame:CGRectMake(70,-10, 320-210, 50)];
    htext.backgroundColor = [UIColor clearColor];
    htext.numberOfLines = 0;
    if (!fromSelf) {
        htext.textAlignment = NSTextAlignmentRight;
    }
    htext.lineBreakMode = NSLineBreakByWordWrapping;
    htext.text = @"位置分享";
    htext.font = [UIFont systemFontOfSize:15];
    //    htext.textColor = [UIColor whiteColor];
    [bubbleText addSubview:htext];
    
    TCLocationMessageBody *lmodel  = (TCLocationMessageBody *)model.body;
    
    //位置信息内容
    UILabel *dizhi = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?70:-10,20, 320-210, 50)];
    //    UILabel *dizhi = [[UILabel alloc] initWithFrame:CGRectMake(70,20, 320-210, 50)];
    dizhi.backgroundColor = [UIColor clearColor];
    dizhi.numberOfLines = 0;
    if (!fromSelf) {
        dizhi.textAlignment = NSTextAlignmentRight;
    }
    dizhi.lineBreakMode = NSLineBreakByWordWrapping;
    dizhi.text = lmodel.address;
    dizhi.font = [UIFont systemFontOfSize:13];
    //    dizhi.textColor = [UIColor whiteColor];
    [bubbleText addSubview:dizhi];
    
    UIImageView *himg = [[UIImageView alloc] initWithFrame:CGRectMake(fromSelf?5:110, 5, 60, 60)];
    //    UIImageView *himg = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 60, 60)];
    himg.image = [UIImage imageNamed:@"ltdili"];
    [bubbleText addSubview:himg];
    
    
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    //绑定事件
    BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH-140, 70)];
    [btn addTarget:self action:@selector(address:) forControlEvents:UIControlEventTouchUpInside];
    btn.model = lmodel;
    [bubbleText addSubview:btn];
    
    return returnView;
    
    
}

//视频
- (UIView *)shipView:(TCMessage *)model from:(BOOL)fromSelf withIndexRow:(NSIndexPath *)indexRow  withPosition:(int)position{
    
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"lthb_y":@"lthb_z" ofType:@"png"]];
    
    bubble = [bubble imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    bubbleImageView.tintColor = [UIColor whiteColor];
    
    
    TCVideoMessageBody *lmodel  = (TCVideoMessageBody *)model.body;
    
    //图片
    UIView *bubbleText = [[UIView alloc] initWithFrame:CGRectMake(fromSelf?10.0f:22.0f, 20.0f,  90, 70)];
    
    NSString *url = lmodel.videoUrl;
    AVPlayerItem *_playItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    AVPlayer *_player = [AVPlayer playerWithPlayerItem:_playItem];
    AVPlayerLayer *_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, 90, 70);
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [bubbleText.layer addSublayer:_playerLayer];
    _players = _player;
    BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 0, 90, 70)];
    btn.play  = _player;
    btn.name = url;
    btn.model = lmodel;
    btn.media = indexRow;
    [btn setImage:[UIImage imageNamed:@"图标---视频播放"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    [bubbleText addSubview:btn];
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+25.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    return returnView;
}
#pragma mark 转赠
- (UIView *)zhuanzeng:(TCMessage *)model from:(BOOL)fromSelf indexPath:(NSInteger)indexPath withPosition:(int)position{
    //计算大小
    NSString *text = @"某某赠送：￥999，恭喜发财,大吉大利";
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    [ImageService imageWithColor:UIColorFromRGB(0xFAFFD4) img:bubble];
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    MLEmojiLabel *bubbleText = [[MLEmojiLabel alloc]initWithFrame:CGRectMake(fromSelf?15.0f:22.0f,10, size.width+10, size.height+10)];
    bubbleText.lineBreakMode = NSLineBreakByCharWrapping;
    bubbleText.isNeedAtAndPoundSign = YES;
    bubbleText.numberOfLines = 0;
    [ValidateHelper ReplaceMLEmojiLabel:text emojilable:bubbleText];
    [bubbleText sizeToFit];
    CGRect backFrame = bubbleText.frame;
    backFrame.size.height += 13+13+5;
    bubbleText.frame = backFrame;
    rh = backFrame.size.height;
    //    [_table reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCRE_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    return returnView;
}
#pragma mark - Video Play
- (void)playVideoWithUrl:(NSString*)strUrl {
    /*
    ShipingBFView * vc = [ShipingBFView new];
    vc.url = strUrl;
    [self presentViewController:vc animated:YES completion:nil];
     */
    
    MPMoviePlayerViewController* con = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:strUrl]];
    [con.moviePlayer prepareToPlay];
    if (self.subPageDelegate) {
        [self.subPageDelegate presentMoviePlayerViewControllerAnimated:con];
    } else {
        [self presentMoviePlayerViewControllerAnimated:con];
    }
    [con.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
    [con.view setBackgroundColor:[UIColor clearColor]];
    con.view.frame = self.view.bounds;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(movieFinishedCallback:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:con.moviePlayer];
    
}

- (void)movieFinishedCallback:(NSNotification*)notify {
    MPMoviePlayerController * theMovie = [notify  object];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:theMovie];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(0.51 * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
                       if (self.subPageDelegate) {
                           if (![((GroupChatVC*)self.subPageDelegate).presentedViewController isBeingDismissed]) {
                               [self.subPageDelegate dismissMoviePlayerViewControllerAnimated];
                           }
                       } else {
                           if (![self.presentedViewController isBeingDismissed]) {
                               [self dismissMoviePlayerViewControllerAnimated];
                           }
                       }
                   });
}
#pragma mark 视频播放
-(void)play:(BaseButton *)btn {
    TCVideoMessageBody *lmodel = btn.model;
    [self playVideoWithUrl:lmodel.videoUrl];
    //    [btn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    //    btn.selected = !btn.selected;
    //    AVPlayer *play = (AVPlayer *)btn.play;
    //    if (!btn.selected) {
    //        [play pause];
    //    }else{
    //        [play play];
    //    }
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotification object:btn];
}
#pragma mark 播放结束通知
-(void)playbackFinished:(NSNotification *)notification
{
    BaseButton *btn = (BaseButton *)notification.object;
    AVPlayer *play = (AVPlayer *)btn.play;
    [play seekToTime:CMTimeMake(0, 1)];
    [btn setImage:[UIImage imageNamed:@"图标---视频播放"] forState:UIControlStateNormal];
}
#pragma mark 图片放大
-(void)picenlarge:(BaseButton *)btn {
    TCMessage *model = [resultArray objectAtIndex:btn.tag];
    TCImageMessageBody *imag = (TCImageMessageBody *)model.body;
    NSMutableArray  *imgdata = [[NSMutableArray alloc]init];
    ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc] init];
    
    ImageProgress * pro = [[ImageProgress alloc] initWithUrl:imag.imgUrlL delegate:self];
    if (!pro.loaded) {
        [pro startDownload];
    }else{
        photo.photoImage =pro.image;
        [imgdata addObject:photo];
        
        // 图片游览器
        ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc] init];
        // 数据源/delegate
        //    pickerBrowser.delegate = self;
        pickerBrowser.status = UIViewAnimationAnimationStatusFade;
        
        // 数据源可以不传，传photos数组 photos<里面是ZLPhotoPickerBrowserPhoto>
        pickerBrowser.photos = imgdata;
        // 是否可以删除照片
        pickerBrowser.editing = NO;
        // 当前选中的值
        pickerBrowser.currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        // 展示控制器
        [pickerBrowser showPickerVc:self];
        
    }
    
}
#pragma mark 红包详情(点击红包消息)
-(void)hongbao:(BaseButton *)btn {
    
    
    [AppDelegate shareDelegate].hbdic = btn.dic;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    HongbaoViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"HongbaoVC"];
    searchResultDetailController.view.backgroundColor = [UIColor clearColor];
    searchResultDetailController.modalPresentationStyle= UIModalPresentationOverFullScreen;
    searchResultDetailController.dic = btn.dic;
    [self presentModalViewController:searchResultDetailController animated:YES];
}
#pragma mark 地址分享详情
-(void)address:(BaseButton *)btn {
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    MapViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"MapVC"];
    searchResultDetailController.model = btn.model;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}

#pragma  mark 点击共享VIEW进入共享
- (IBAction)viewTogongxiang:(UIButton *)sender {
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    PositionViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"PositionViewController"];
    if ([AppDelegate shareDelegate].meetingNum != nil) {
        searchResultDetailController.meetingNumbers = [AppDelegate shareDelegate].meetingNum;
    }
    searchResultDetailController.isjon = YES;
    searchResultDetailController.user = [AppDelegate shareDelegate].gxuser;
    searchResultDetailController.deleagte = self;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
-(void)zhongzhi{
    _gxview.hidden = YES;
}
#pragma mark 消息体进入共享
-(void)togongxiang:(BaseButton *)btn{
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    if (btn.model) {
        LoginResponseModel *user = btn.model;
        [dic setObject:user.uid forKey:@"groupId"];
    }else{
        [dic setObject:[btn.dic objectForKey:@"groupId"] forKey:@"groupId"];
    }
    
    [[ECDevice sharedInstance].meetingManager joinMeeting:[btn.dic objectForKey:@"meetingNumbers"] ByMeetingType:ECMeetingType_MultiVoice andMeetingPwd:@"yimisns" completion:^(ECError *error, NSString *meetingNumber) {
        if (error.errorCode == ECErrorType_NoError)
        {
            [[BusinessService shareInstance] posshare_enterGroup:dic success:^(id result) {
                UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                             bundle:[NSBundle mainBundle]];
                PositionViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"PositionViewController"];
                searchResultDetailController.meetingNumbers = [btn.dic objectForKey:@"meetingNumbers"];
                [AppDelegate shareDelegate].meetingNum = searchResultDetailController.meetingNumbers;
                searchResultDetailController.user = result;
                [AppDelegate shareDelegate].gxuser = result;
                searchResultDetailController.deleagte = self;
                _gxview.hidden = NO;
                [self.navigationController pushViewController:searchResultDetailController animated:YES];
                
                
                
            } failure:^(id result) {
                [SVProgressHUD showErrorWithStatus:result];
            }];
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"当前位置共享已关闭"];
        }
    }];
    
    
}


#pragma mark 位置共享退出
-(void)endQgx:(NSNotification *)not{
    
}
#pragma mark 群共享通知
-(void)initQgx:(NSNotification *)not{
    //    gxview = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCRE_WIDTH, 40)];
    //    gxview.backgroundColor = UIColorFromRGB(0x9CD79F);
    //
    //    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 15, 20)];
    //    img.image = [UIImage imageNamed:@"ltgxtb"];
    //    [gxview addSubview:img];
    //
    //
    //    UIImage *nimg = [UIImage imageNamed:@"next"];
    //    BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, 40)];
    //    [btn setImage:[ImageService imageWithColor:[UIColor whiteColor] img:nimg] forState:UIControlStateNormal];
    //    btn.imageEdgeInsets = UIEdgeInsetsMake(0, SCRE_WIDTH - 20, 0, 0);
    //    TCNotify *noty = not.object;
    //    NSMutableDictionary *dic = [JsonService jsonObjectWithString:noty.content];
    //    [[AppDelegate shareDelegate]refuser:[dic objectForKey:@""] success:^(id as) {
    //        [btn addTarget:self action:@selector(togongxiang:) forControlEvents:UIControlEventTouchUpInside];
    //        btn.model = as;
    //        [gxview addSubview:btn];
    //        [self.view addSubview:gxview];
    //    }];
}
#pragma UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return resultArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else{
        for (UIView *cellView in cell.subviews){
            [cellView removeFromSuperview];
        }
    }
    //TCMessage *mesmodel = [resultArray objectAtIndex:indexPath.row];
    TCMessage *mesmodel = resultArray[indexPath.row];
    //创建头像
    if (mesmodel.isSendByMe){//右
        UIImageView *photo = [[UIImageView alloc]initWithFrame:CGRectMake(SCRE_WIDTH-60, 10, 50, 50)];
        [cell addSubview:photo];
        photo.layer.cornerRadius = photo.frame.size.width/2;
        photo.clipsToBounds = YES;
        [photo sd_setImageWithURL:[NSURL URLWithString:mesmodel.from.head]
                 placeholderImage:[UIImage imageNamed:@"notimg"]];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(SCRE_WIDTH-170, -8, 120, 30)];
        label.text =  [ValidateHelper timeStringWith:mesmodel.time multiLine:NO];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:13];
        [cell addSubview:label];
        UIView *view;
        if (mesmodel.typeFile == forFileText) {
            view = [self bubbleView:mesmodel.bodyText.content  from:YES withPosition:65 indexPath:indexPath];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forFileImage){
            view = [self tupianView:mesmodel from:YES cell:cell withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forFileVoice){
            view = [self yuyinView:mesmodel from:YES withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
            
        }else if (mesmodel.typeFile == forFileLocation){
            view = [self weizhiView:mesmodel from:YES withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forREDPAPER){
            view = [self hongbaoView:mesmodel from:YES withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
            CGRect c = cell.frame;
            c.size.height = view.frame.size.height+20;
            cell.frame = c;
        }else if(mesmodel.typeFile == forSEND){
            view = [self zhuanzeng:mesmodel from:YES indexPath:indexPath.row withPosition:65];
            [cell addSubview:view];
        }
        else if(mesmodel.typeFile == forFileVideo){
            view = [self shipView:mesmodel from:YES withIndexRow:indexPath withPosition:65];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forGongXiang){
            view = [self GXweizhiView:mesmodel from:YES withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
        }
        CGRect c = cell.frame;
        c.size.height = view.frame.size.height+20;
        cell.frame = c;
        if(mesmodel.state==forMessageStateNormal){
            NSLog(@"index.row%ld:成功",(long)indexPath.row);
        }else if (mesmodel.state==forMessageStateError){
            NSLog(@"失败");
        }else if (mesmodel.state==forMessageStateHavent){
            NSLog(@"未发送");
        }
        if (mesmodel.state == forMessageStateHavent) {
            UIActivityIndicatorView  *progressInd=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:
                                                   UIActivityIndicatorViewStyleWhite];
            progressInd.frame = CGRectMake(view.frame.origin.x-10, view.frame.origin.y+15, 15, 15);
            [cell addSubview:progressInd];
            [progressInd startAnimating];
        }else if (mesmodel.state==forMessageStateError){
            BaseButton *cfBtn = [[BaseButton alloc]initWithFrame:CGRectMake(view.frame.origin.x-15, view.frame.origin.y+15, 15, 15)];
            [cfBtn setImage:[UIImage imageNamed:@"msgerror"] forState:UIControlStateNormal];
            cfBtn.tag = indexPath.row;
            [cfBtn addTarget:self action:@selector(againAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:cfBtn];
        }
    }else{//左
        UIImageView *photo = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
        [cell addSubview:photo];
        photo.layer.cornerRadius = photo.frame.size.width/2;
        photo.clipsToBounds = YES;
        [photo sd_setImageWithURL:[NSURL URLWithString:mesmodel.from.head]
                 placeholderImage:[UIImage imageNamed:@"notimg"]];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, -8, 120, 30)];
        label.text =   [ValidateHelper timeStringWith:mesmodel.time multiLine:NO];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:13];
        [cell addSubview:label];
        UIView *view;
        if (mesmodel.typeFile == forFileText) {
            view = [self bubbleView:mesmodel.bodyText.content  from:NO withPosition:65 indexPath:indexPath];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forFileImage){
            view = [self tupianView:mesmodel from:NO cell:cell withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forFileVoice){
            view = [self yuyinView:mesmodel from:NO withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
            
        }else if (mesmodel.typeFile == forFileLocation){
            view = [self weizhiView:mesmodel from:NO withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forREDPAPER){
            view = [self hongbaoView:mesmodel from:NO withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
        }else if(mesmodel.typeFile == forSEND){
            view = [self zhuanzeng:mesmodel from:NO indexPath:indexPath.row withPosition:65];
            [cell addSubview:view];
        }else if(mesmodel.typeFile == forFileVideo){
            view = [self shipView:mesmodel from:NO withIndexRow:indexPath withPosition:65];
            [cell addSubview:view];
        }else if (mesmodel.typeFile == forGongXiang){
            view = [self GXweizhiView:mesmodel from:NO withIndexRow:indexPath.row withPosition:65];
            [cell addSubview:view];
        }
        
        CGRect c = cell.frame;
        c.size.height = view.frame.size.height+15;
        cell.frame = c;
    }
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    
}

- (IBAction)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}
#pragma mark 重新发送
-(void)againAction:(BaseButton *)btn{
    UIActionSheet *alrt = [[UIActionSheet alloc]initWithTitle:@"是否重新发送？" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alrt.tag = btn.tag;
    [alrt showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)sender didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (sender.tag == 11) {
        if (buttonIndex == 0) {
            
            
            NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
            [[BusinessService shareInstance] posshare_enterGroup:dic success:^(id result) {
                UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                             bundle:[NSBundle mainBundle]];
                PositionViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"PositionViewController"];
                searchResultDetailController.user = result;
                searchResultDetailController.deleagte = self;
                [self.navigationController pushViewController:searchResultDetailController animated:YES];
                
            } failure:^(id result) {
                [SVProgressHUD showErrorWithStatus:result];
            }];
        }
        if (buttonIndex == 1) {
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                         bundle:[NSBundle mainBundle]];
            AddMapViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddMapVC"];
            searchResultDetailController.datelate = self;
            [self.navigationController pushViewController:searchResultDetailController animated:YES];
        }
        return;
    }
    if(buttonIndex != 1){
        TCMessage* itemM = [resultArray objectAtIndex:sender.tag];
        itemM.state = forMessageStateHavent;
        [resultArray removeObjectAtIndex:sender.tag];
        [resultArray insertObject:itemM atIndex:sender.tag];
        [self scrollToBottom];
        [[ThinkChat instance] sendMessage:itemM attach:nil];
        
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isKindOfClass:[UITextView class]]) {
        return;
    }
    isUp = NO;
    //    if (self.inputView) {
    //        [self up:NO];
    //        [self.inputView.emotionView removeFromSuperview];
    //    }
    if (self.emojiView) {
        [self up:NO];
        [self.emojiView removeFromSuperview];
    }
    [self.view endEditing:YES];
}

- (void)tapClick
{
    isUp = NO;
    if (self.emojiView) {
        [self up:NO];
        [self.emojiView removeFromSuperview];
    }
    [self.view endEditing:YES];
}

#pragma  mark  展开聊天工具
- (IBAction)zkChatAction:(UIButton *)sender {
    
    if (sender.titleLabel.text.length != 0) {
        [self senderAction:sender];
        return;
    }
    
    [self.view endEditing:YES];
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        isUp = NO;
        //        if (self.inputView) {
        //            [self up:NO];
        //            [self.inputView.emotionView removeFromSuperview];
        //        }
        if (self.emojiView) {
            [self up: NO];
            [self.emojiView removeFromSuperview];
        }
        
        _sender_btn.layer.cornerRadius = 4;
        
        CGRect f = _bview.frame;
        f.origin.y = f.origin.y - 100;
        _bview.frame = f;
        
        CGRect c = _table.frame;
        c.size.height = f.origin.y-50;
        _table.frame = c;
        
        
        
    }else{
        
        [self.view endEditing:YES];
        
        
        
        _sender_btn.layer.cornerRadius = 4;
        CGRect f = _bview.frame;
        f.origin.y = f.origin.y + 100;
        _bview.frame = f;
        
        
        CGRect c = _table.frame;
        c.size.height = _bview.frame.origin.y-50;
        _table.frame = c;
        
    }
    [self scrollToBottom];  //xhw2018-1-29
    /*
    [self.view endEditing:YES];
    sender.selected = !sender.selected;
    if (sender.selected) {
        isUp = NO;
        if (inputView) {
  
            [self up:NO];
            [inputView removeFromSuperview];
            inputView = nil;
        }
        _sender_btn.layer.cornerRadius = 4;
        CGRect f = _bview.frame;
        f.origin.y = f.origin.y - 100;
        _bview.frame = f;
        
        CGRect c = _table.frame;
        c.size.height = f.origin.y-50;
        _table.frame = c;
    }else{
        
        [self.view endEditing:YES];
        
        _sender_btn.layer.cornerRadius = 4;
        CGRect f = _bview.frame;
        f.origin.y = f.origin.y + 100;
        _bview.frame = f;
        
        CGRect c = _table.frame;
        c.size.height = f.origin.y-50;
        _table.frame = c;
    }
    [self scrollToBottom];
     */
}
-(void)heidGJ{
    _sender_btn.layer.cornerRadius = 4;
    CGRect f = _bview.frame;
    f.origin.y = f.origin.y + 100;
    _bview.frame = f;
    
    CGRect t = _table.frame;
    t.size.height = f.origin.y-50;
    _table.frame = t;
}

#pragma  mark 拍摄
- (IBAction)videoAction:(UIButton *)sender {
    /*
    [AppDelegate shareDelegate].Close = NO;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"KP"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"VideoViewController"];
    viewcv.modalPresentationStyle= UIModalPresentationOverFullScreen;
    [AppDelegate shareDelegate].sptype = 1;
    [self presentViewController:viewcv animated:YES completion:nil];
     */
    
    
//    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//
//    if (authStatus == AVAuthorizationStatusRestricted ||
//
//        authStatus ==AVAuthorizationStatusDenied){
//        
//        [QMUITips showError:@"请确认已打开相机权限" inView:self.view hideAfterDelay:3];
//        return;
//
//    }
//
//    [self presentViewController:self.picker animated:YES completion:nil];
    
    self.isVideo = YES;
    [self presentViewController:self.addFileVC animated:YES completion:nil]; //xhw2018-1-29加
    
    /*
    WeakSelf
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"拍摄" message:@"拍照或摄像" preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        weakSelf.picker.mediaTypes = @[(NSString *)kUTTypeImage];
        weakSelf.picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        
        [weakSelf presentViewController:weakSelf.picker animated:YES completion:nil];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        weakSelf.picker.mediaTypes = @[(NSString *)kUTTypeMovie];
        weakSelf.picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
        [weakSelf presentViewController:weakSelf.picker animated:YES completion:nil];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
    */
}
#pragma mark 红包
- (IBAction)hongbaoAction:(id)sender {
    NSString *uid;
    if (self.tcs) {
        uid = _tcs.ID;
    }else{
        uid = _model.ID;
    }
    [self.view endEditing:YES];
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    AddHongbaoView *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddHongbaoView"];
    searchResultDetailController.degetage = self;
    searchResultDetailController.uid = uid;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    
    
}
#pragma mark  红包回调
-(void)didSelectHongbao:(NSMutableDictionary *)dic{
    TCMessage* itemM = [self newMessage];
    itemM.typeFile = forREDPAPER;
    [itemM.extDic addEntriesFromDictionary:dic];
    //    [itemM setExtendValue: forKey:@"hongbao"];
    itemM.body = [[TCMessageBody alloc] init];
    [resultArray addObject:itemM];
    
    //    [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    //    [self scrollToBottom];
    [[AppDelegate shareDelegate]sendMessage:itemM];
}
#pragma  mark 位置
- (IBAction)weizhiAction:(UIButton *)sender {
    UIActionSheet *seet = [[UIActionSheet alloc]initWithTitle:@"位置" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"共享位置",@"选择位置", nil];
    seet.tag = 11;
    [seet showInView:self.view];
    
    
}
#pragma mark 地图选择回调
-(void)selectAddress:(NSMutableDictionary *)address{
    addres = address;
    TCMessage* itemM = [self newMessage];
    itemM.body = [[TCLocationMessageBody alloc] init];
    itemM.typeFile = forFileLocation;
    itemM.bodyLocation.lat = [[address objectForKey:@"latitude"] doubleValue];
    itemM.bodyLocation.lng = [[address objectForKey:@"longitude"] doubleValue];
    itemM.bodyLocation.address = [address objectForKey:@"name"];
    
    [resultArray addObject:itemM];
    
    //    [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    //    [_table reloadData];
    //    [self scrollToBottom];
    [[AppDelegate shareDelegate]sendMessage:itemM];
    
}
#pragma mark 转赠
- (IBAction)zhuanzAction:(id)sender {
    
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"DonationVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    
}
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (istablescoolr != 1) {
        if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
            [_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:resultArray.count-1   inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            istablescoolr = 1;
        }
    }
}
-(void)viewDidAppear:(BOOL)animated{
    if (self.messmodelList.count!=0) {
        [_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:resultArray.count-1   inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    [self registerForKeyboardNotifications];
    return YES;
}
#pragma mark 创建共享成功后发送共享消息
-(void)sendgx:(NSNotification *)not{
    NSMutableDictionary *gx = not.object;
    TCMessage* itemM = [self newMessage];
    itemM.typeFile = forGongXiang;
    [itemM.extDic addEntriesFromDictionary:gx];
    itemM.body = [[TCTextMessageBody alloc] init];
    [itemM.body setExtendValue:@"[共享]" forKey:@"body扩展"];
    [resultArray addObject:itemM];
    [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self scrollToBottom];
    [[AppDelegate shareDelegate]sendMessage:itemM];
    
    NSMutableDictionary *dic = not.object;
    
    gxuser = [AppDelegate shareDelegate].user;
    gxuser.id = [dic objectForKey:@"groupId"];
    [AppDelegate shareDelegate].meetingNum = [dic objectForKey:@"meetingNumbers"];
    [AppDelegate shareDelegate].gxuser = gxuser;
    
    _gxview.hidden = NO;
    
}
#pragma mark 将要离开当前界面
-(void)viewWillDisappear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
    
    [inputView removeFromSuperview];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(sendgx:)
     name:@"sendgongxiang"
     object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearSession:) name:@"clearSession" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initGroupList:) name:@"groupList" object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(psend:)
     name:@"psendg"
     object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(pzsend:)
     name:@"pzsendg"
     object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(initQgx:)
     name:@"initQgxG"
     object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(endQgx:)
     name:@"endQgxG"
     object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gongxiangzhongzhi:) name:@"gongxiangzhongzhig" object:nil];
}
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShownHe:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)keyboardWasShownHe:(NSNotification*)noti{
    //改变window的背景颜色
    self.view.window.backgroundColor = _table.backgroundColor;
    //  键盘退出的frame
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGRect keyboardFrame;
    [[noti.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardFrame];
    
    //键盘实时y
    CGFloat keyY = frame.origin.y;
    if (self.emojiView) { //xhw20181-1-29加
//    if (inputView) { //xhw20181-1-29注释
        //        CGRect f = _table.frame;
        //        f.size.height = SCRE_HEIGHT - h;
        //        _table.frame = f;
        keyY = SCRE_HEIGHT;
        isUp = NO;
//        [[NSNotificationCenter defaultCenter] removeObserver:self]; //xhw2018-1-29注释
    }else
        if(isUp){
            keyY = SCRE_HEIGHT;
            isUp = NO;
            [[NSNotificationCenter defaultCenter] removeObserver:self];
        }else{
            h = frame.size.height;
        }
    if (_gongju.selected) {
        CGRect f = _bview.frame;
        f.origin.y = f.origin.y + 100;
        _bview.frame = f;
        _gongju.selected = NO;
        CGRect c = _table.frame;
        c.size.height = f.origin.y-50;
        _table.frame = c;
        [_content_Text becomeFirstResponder];
    }else{
        //        CGRect f = _bview.frame;
        //        f.origin.y = f.origin.y - 100;
        //        _bview.frame = f;
        //        _gongju.selected = YES;
    }
    
    //屏幕的高度
    CGFloat screenH = [[UIScreen mainScreen] bounds].size.height;
    
    //动画时间
    CGFloat keyDuration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //执行动画
    [UIView animateWithDuration:keyDuration animations:^{
        //        [[[UIApplication sharedApplication] windows] firstObject].transform = CGAffineTransformMakeTranslation(0, keyY - screenH);
        _bgview.transform = CGAffineTransformMakeTranslation(0, keyY - screenH);
    }];
    
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if ([scrollView isKindOfClass:[UITextView class]]) {
//        return;
//    }
//    isUp = NO;
//    if (inputView) {
//        [self up:NO];
//        [inputView removeFromSuperview];
//        inputView = nil;
//    }
//    [self.view endEditing:YES];
//}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    if([_content_Text.text trim].length == 0 ){
        return NO;
    }
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
//视图上移的方法
- (void)  up: (BOOL) up
{
    //  键盘退出的frame
//    CGRect frame = inputView.frame;
    CGRect frame = self.emojiView.frame;
    //键盘实时y
    CGFloat keyY = frame.origin.y;
    if (!up) {
        keyY = SCRE_HEIGHT;
    }
    
    //屏幕的高度
    CGFloat screenH = [[UIScreen mainScreen] bounds].size.height;
    //动画时间
    CGFloat keyDuration = 0.25;
    //执行动画
    [UIView animateWithDuration:keyDuration animations:^{
        _table.transform = CGAffineTransformMakeTranslation(0, keyY - screenH);
        _bview.transform = CGAffineTransformMakeTranslation(0, keyY - screenH);
    }];
}

-(UIView *)toolbar{
    if (!_toolbar) {
        _toolbar = [[UIView alloc] init];
        //        _toolbar.frame = CGRectMake(0, CGRectGetMinY(_inputView.emotionView.frame) - 44, CGRectGetWidth(self.view.bounds), 44);
        _toolbar.frame = CGRectMake(0, CGRectGetMaxX(_emojiView.frame)-44, CGRectGetWidth(self.view.bounds), 44);
        _toolbar.qmui_borderPosition = QMUIBorderViewPositionTop;
        _toolbar.backgroundColor = UIColorWhite;
        
    }
    return _toolbar;
}

- (EmotionInputView *)emojiView {
    if (!_emojiView) {
        [self.view addSubview:self.toolbar];
        
        _emojiView = [[EmotionInputView alloc]initWithDelegate:self];
        _emojiView.backgroundColor = [UIColor whiteColor];
        _emojiView.frame = CGRectMake(0, SCRE_HEIGHT-192, SCRE_WIDTH, 192);
    }
    return _emojiView;
}

- (void)emotionInputView:(id)sender output:(NSString *)str {
    if (_content_Text) {
        _content_Text.text = [NSString stringWithFormat:@"%@%@",_content_Text.text,[EmotionInputView emojiText4To5:str]];
    }
}

#pragma mark 表情
- (IBAction)bqAction:(UIButton *)sender {
    if (_gongju.selected) {
        CGRect f = _bview.frame;
        f.origin.y = f.origin.y + 100;
        _bview.frame = f;
        
        _gongju.selected = NO;
    }
    
    //xhw2018-1-29加
    [_gongju setTitle:@"发送" forState:UIControlStateNormal];
    [_gongju setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    _gongju.backgroundColor = UIColorFromRGB(0x83D06C);
    
    //    if (!self.inputView) {
    //    [self.view addSubview:self.inputView.emotionView];
    [self.view addSubview:self.emojiView];
    [self up:YES];
    //xhw2018-1-29加
    
    
    /*
    if (!inputView) {
        CGRect c = _table.frame;
        c.size.height = _bview.frame.origin.y-50;
        _table.frame = c;
        inputView = [[KYExpressionInputView alloc] init];
        inputView.frame = CGRectMake(0, SCRE_HEIGHT-inputView.frame.size.height+5, SCRE_WIDTH, inputView.frame.size.height);
        inputView.toolbarColor = [UIColor whiteColor];
        inputView.backgroundColor = [UIColor whiteColor];
        
        inputView.toolbar.hidden = YES;
        [inputView setToolbarSendButtonHidden:YES animated:NO];
        [inputView addToolbarItemWithImage:nil title:nil items:[AppDelegate shareDelegate].emojiItems row:KYUIntegerOrientationMake(4, 5) column:KYUIntegerOrientationMake(8, 14) itemSize:KYSizeOrientationMake(CGSizeMake(36, 36), CGSizeMake(36, 36)) itemSpacing:KYFloatOrientationMake(6, 8)];
        inputView.delegate = self;
        [self.view addSubview:inputView];
        [self.view bringSubviewToFront:inputView];
//        [[[[UIApplication sharedApplication] windows] firstObject] addSubview:inputView];
        [self up:YES];
    }
    */
    
    
    [self.view endEditing:YES];
    isUp = YES;
    
    
    
}

- (void)inputView:(KYExpressionInputView *)inputView didSelectExpression:(id<KYExpressionData>)expression {
    
    NSString *picName = [expression imageUrl];
    NSLog(@"%@",picName);
    //Create emoji attachment
    EmojiTextAttachment *emojiTextAttachment = [EmojiTextAttachment new];
    emojiTextAttachment.emojiTag =[NSString stringWithFormat:@"[%@]",picName];
    //Set tag and image
    emojiTextAttachment.image = [UIImage imageNamed:picName];
    emojiTextAttachment.emojiSize = 20;
    emojiTextAttachment.bql = -5;
    
    //Insert emoji image
    [_content_Text.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:emojiTextAttachment]
                                              atIndex:_content_Text.selectedRange.location];
    
    //Move selection location
    _content_Text.selectedRange = NSMakeRange(_content_Text.selectedRange.location + 1, _content_Text.selectedRange.length);
}


-(TCMessage *)newMessage{
    TCMessage* msg = [TCMessage newMessage];
    msg.typeChat = forChatTypeRoom;
    msg.typeFile = 1;
    msg.state = forMessageStateHavent;
    msg.from.name = [AppDelegate shareDelegate].user.nickname;
    msg.from.ID = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
    msg.from.head = [AppDelegate shareDelegate].user.headsmall;
    if (_model) {
        msg.to.ID =[NSString stringWithFormat:@"%@",_model.uid];
        msg.to.name = _model.name;
        msg.to.head = _model.headImgUrlL;
        
    }else{
        msg.to.ID = [NSString stringWithFormat:@"%@",self.tcs.ID];
        msg.to.name = self.tcs.name;
        msg.to.head = self.tcs.head;
    }
    msg.typeFile = 1;
    return msg;
}
#pragma mark 发送
- (IBAction)senderAction:(UIButton *)sender {
    if ([sender.titleLabel.text  isEqual: @"发送"]) {
        
    }
    else {
        [self zkChatAction:sender];
        return;
    }
    
    if(self.changeButton.selected){//语音
        [self actionBarTalkFinished];
        return;
    }
    
    _gongju.backgroundColor = [UIColor clearColor];
    _gongju.titleLabel.text = @"";
    [_gongju setTitle:@"" forState:UIControlStateNormal];
    [_gongju setImage:[UIImage imageNamed:@"ltfszk"] forState:UIControlStateNormal];

    isUp = NO;
    if (self.emojiView) {
        [self up:NO];
        [self.emojiView removeFromSuperview];
    }
    
//    if (inputView) {
//        [self up:NO];
//        [inputView removeFromSuperview];
//        inputView = nil;
//    }
    [self.view endEditing:YES];
    TCMessage* msg = [TCMessage newMessage];
    msg.typeChat = forChatTypeRoom;
    msg.typeFile = 1;
    msg.from.name = [AppDelegate shareDelegate].user.nickname;
    msg.from.ID = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
    msg.from.head = [AppDelegate shareDelegate].user.headsmall;
    if (_model) {
        msg.to.ID =[NSString stringWithFormat:@"%@",_model.ID];
        NSLog(@"xhw->GroupChatVC->sendMsg->model.id:%@",_model.ID);
        msg.to.name = _model.name;
        if (headimgs.length == 0 ) {
            [self gethead];
        }
        msg.to.head = headimgs;
        
    }else{
        msg.to.ID = [NSString stringWithFormat:@"%@",self.tcs.ID];
        NSLog(@"xhw->GroupChatVC->sendMsg->self.tcs.id:%@",self.tcs.ID);
        msg.to.name = self.tcs.name;
        if (headimgs.length == 0 ) {
            [self gethead];
        }
        msg.to.head = headimgs;
    }
    NSLog(@"xhw->GroupChatVC->sendMsg->msg.to.id:%@",msg.to.ID);
    NSLog(@"xhw->GroupChatVC->sendMsg->msg.ID:%@",msg.ID);
    msg.typeFile = 1;
    msg.state = forMessageStateHavent;
    msg.body = [[TCTextMessageBody alloc] init];
    msg.bodyText.content = [EmotionInputView encodeMessageEmoji:[_content_Text.textStorage getPlainString]];
    [msg.from setExtendValue:@"从哪儿来的?" forKey:@"from扩展"];
    [msg.to setExtendValue:@"到哪儿去?" forKey:@"to扩展"];
    [msg.body setExtendValue:@"消息体的扩展" forKey:@"body扩展"];
    [msg setExtendValue:@"消息本身的扩展" forKey:@"msg扩展"];
    _content_Text.text = nil;
    [resultArray addObject:msg];
    if (resultArray.count == 1) {
        [_table reloadData];
    }
    else {
       [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
    
    
    [self scrollToBottom];
    [[AppDelegate shareDelegate]sendMessage:msg];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initGroupList:) name:@"groupList" object:nil];
    
}
- (void)scrollToBottom
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initGroupList:) name:@"groupList" object:nil];
    NSInteger section  = [self numberOfSectionsInTableView:_table] - 1;
    if (section >= 0) {
        NSInteger row = [self tableView:_table numberOfRowsInSection:section] -1;
        if (row >= 0) {
            NSIndexPath * indxPath= [NSIndexPath indexPathForRow:row inSection:section];
            [_table scrollToRowAtIndexPath:indxPath atScrollPosition:UITableViewScrollPositionBottom  animated:YES];
        }
    }
}


#pragma mark 相机
- (IBAction)potoAction:(id)sender {
    [self.view endEditing:YES];
    //    UIActionSheet *sctionsheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"照相" otherButtonTitles:@"选择相册", nil];
    //    sctionsheet.tag = 99;
    //    [sctionsheet showInView:self.view];
    /*
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusRestricted ||
        
        authStatus ==AVAuthorizationStatusDenied){
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"加载相机失败，请确认隐私设置中相机权限已打开！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        
    }
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:NO completion:^{}];
    */
    
    //xhw2018-1-29改:聊天界面中选择图片都统一成这种形式的
    self.isVideo = NO;
    [self presentViewController:self.addFileVC animated:YES completion:nil];
}
//xhw2018-1-29改:聊天界面中选择图片都统一成这种形式的
- (AddFileViewController *)addFileVC {
    if (!_addFileVC) {
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"Dynaminc"
                                                                     bundle:[NSBundle mainBundle]];
        _addFileVC = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddFileViewController"];
        _addFileVC.InType = 2;
        if (self.isVideo) {
            
        }else {
            _addFileVC.hideVideo = YES;
        }
        _addFileVC.hideVideo = NO;
        _addFileVC.delegate = self;
    }
    return _addFileVC;
}

-(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag != 99 ) {
        return;
    }
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusRestricted ||
        
        authStatus ==AVAuthorizationStatusDenied){
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"加载相机失败，请确认隐私设置中相机权限已打开！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        
    }
    if (buttonIndex == 0) {
        UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
        imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerVC.delegate = self;
        imagePickerVC.allowsEditing = YES;
        [self presentViewController:imagePickerVC
                           animated:NO
                         completion:nil];
        
    }
    if (buttonIndex == 1) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:NO completion:^{}];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    if ([info[UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeMovie]) {
        
        NSLog(@"我在录像 录完了");
        
        //        保存视频到相册
        NSLog(@"%@",info[UIImagePickerControllerMediaType]);
        //UISaveVideoAtPathToSavedPhotosAlbum(info[UIImagePickerControllerMediaType], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        [self psend:info[UIImagePickerControllerMediaURL]];
        
    }
    
    if ([info[UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeImage]) {
        
        
        
        UIImage * imgGet = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        if (picker == self.picker) {
            NSLog(@"%@",info);
            sendImage = imgGet;
            [self pzsend:sendImage];
            
        }else{
            if (imgGet) {
                imgGet = [UIImage rotateImage:imgGet];
                
                UIImage* imgL = [imgGet resizeImageGreaterThan:1024];
                NSData* dataL = UIImageJPEGRepresentation(imgL, 0.4);
                NSString * pathL = [NSString stringWithFormat:@"%@/tmp/IMG%.0f.jpg", NSHomeDirectory(), [NSDate timeIntervalSinceReferenceDate] * 1000];
                [dataL writeToFile:pathL atomically:YES];
                
                UIImage* imgS = [imgL resizeImageGreaterThan:200];
                NSData* dataS = UIImageJPEGRepresentation(imgS, 0.4);
                NSString * pathS = [NSString stringWithFormat:@"%@/tmp/IMG%.0f.jpg", NSHomeDirectory(), [NSDate timeIntervalSinceReferenceDate] * 1000];
                [dataS writeToFile:pathS atomically:YES];
                
                TCMessage* itemM = [self newMessage];
                itemM.body = [[TCImageMessageBody alloc] init];
                itemM.typeFile = forFileImage;
                itemM.bodyText.content = @"";
                
                itemM.bodyImage.imgUrlL = pathL;
                itemM.bodyImage.imgUrlS = pathS;
                itemM.bodyImage.imgWidth = imgS.size.width;
                itemM.bodyImage.imgHeight = imgS.size.height;
                NSData* data = [NSData dataWithContentsOfFile:itemM.bodyImage.imgUrlL];
                
                [resultArray addObject:itemM];
                if (resultArray.count>1) {
                    
                    [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                }
                [self scrollToBottom];
                
                [[AppDelegate shareDelegate]sendMessage:itemM];
                
            }
        }
        
        
        //UIImageWriteToSavedPhotosAlbum(imgGet, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }
    
    
    [picker dismissViewControllerAnimated:YES completion:nil];
/*
    UIImage * imgGet = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (imgGet) {
        imgGet = [UIImage rotateImage:imgGet];
        
        UIImage* imgL = [imgGet resizeImageGreaterThan:1024];
        NSData* dataL = UIImageJPEGRepresentation(imgL, 0.4);
        NSString * pathL = [NSString stringWithFormat:@"%@/tmp/IMG%.0f.jpg", NSHomeDirectory(), [NSDate timeIntervalSinceReferenceDate] * 1000];
        [dataL writeToFile:pathL atomically:YES];
        
        UIImage* imgS = [imgL resizeImageGreaterThan:200];
        NSData* dataS = UIImageJPEGRepresentation(imgS, 0.4);
        NSString * pathS = [NSString stringWithFormat:@"%@/tmp/IMG%.0f.jpg", NSHomeDirectory(), [NSDate timeIntervalSinceReferenceDate] * 1000];
        [dataS writeToFile:pathS atomically:YES];
        
        TCMessage* itemM = [self newMessage];
        itemM.body = [[TCImageMessageBody alloc] init];
        itemM.typeFile = forFileImage;
        itemM.bodyImage.imgUrlL = pathL;
        itemM.bodyImage.imgUrlS = pathS;
        itemM.bodyImage.imgWidth = imgS.size.width;
        itemM.bodyImage.imgHeight = imgS.size.height;
        NSData* data = [NSData dataWithContentsOfFile:itemM.bodyImage.imgUrlL];
        
        [resultArray addObject:itemM];
        
        //        [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        //        [self scrollToBottom];
        [[AppDelegate shareDelegate]sendMessage:itemM];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initGroupList:) name:@"groupList" object:nil];
        
    }
    [picker dismissViewControllerAnimated:YES completion:^{
    }];*/
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:NO completion:nil];
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    NSString *new = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger res = 1-[new length];
    if(res != 1){
        [_gongju setTitle:@"发送" forState:UIControlStateNormal];
        [_gongju setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        _gongju.backgroundColor = UIColorFromRGB(0x83D06C);
        [_gongju addTarget:self action:@selector(senderAction:) forControlEvents:UIControlEventTouchUpInside];
        return YES;
    }
    else{
        _gongju.backgroundColor = [UIColor clearColor];
        _gongju.titleLabel.text = @"";
        [_gongju setTitle:@"" forState:UIControlStateNormal];
        [_gongju setImage:[UIImage imageNamed:@"ltfszk"] forState:UIControlStateNormal];
        [_gongju addTarget:self action:@selector(zkChatAction:) forControlEvents:UIControlEventTouchUpInside];
        return YES;
    }
    
}

#pragma mark 语音
- (IBAction)changeButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.sender_btn.hidden = !self.sender_btn.hidden;
    self.content_Text.hidden = !self.content_Text.hidden;
}

//  button1普通状态下的背景色
- (void)button1BackGroundNormal:(UIButton *)sender
{
    sender.backgroundColor = colorBG;
}
//  button1高亮状态下的背景色
- (void)button1BackGroundHighlighted:(UIButton *)sender
{
    sender.backgroundColor = UIColorMake(197, 198, 201);
}



- (IBAction)btnTalkTouchBegin:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn.titleLabel.text.length != 0) {
//        return;
    }
    [self actionBarTalkStateChanged:TalkStateTalking];
}

- (IBAction)btnTalkTouchCancel:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn.titleLabel.text.length != 0) {
//        return;
    }
    [self actionBarTalkStateChanged:TalkStateNone];
}

- (IBAction)btnTalkTouchEnd:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn.titleLabel.text.length != 0) {
//        return;
    }
    [self actionBarTalkFinished];
}

- (IBAction)btnTalkDragInside:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn.titleLabel.text.length != 0) {
//        return;
    }
    [self actionBarTalkStateChanged:TalkStateTalking];
}

- (IBAction)btnTalkDragOutside:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (btn.titleLabel.text.length != 0) {
//        return;
    }
    [self actionBarTalkStateChanged:TalkStateCanceling];
}


- (void)actionBarTalkStateChanged:(TalkState)sts {
    if (sts == TalkStateTalking) {
        recordView.hidden = NO;
    } else if (sts == TalkStateCanceling) {
        recordView.hidden = NO;
    } else {
        recordView.hidden = YES;
    }
    recordView.state = sts;
}

- (void)actionBarTalkFinished {
    recordView.hidden = YES;
    [recordView recordEnd];
}
#pragma mark - TalkingRecordViewDelegate

- (void)recordView:(TalkingRecordView*)sender didFinish:(NSString*)path duration:(NSTimeInterval)du {
    TCDemoLog(@"record did finish %@, duration: %.0f", path, du);
    if (du > 60.0) {
        [SVProgressHUD showErrorWithStatus:@"录音时间过长"];
        
    } else if (du > 2.0) {
        TCMessage* itemM = [self newMessage];
        
        itemM.body = [[TCVoiceMessageBody alloc] init];
        itemM.typeFile = forFileVoice;
        itemM.bodyVoice.voiceTime = du;
        itemM.bodyVoice.voiceUrl = path;
        
        [resultArray addObject:itemM];
        
        [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        [self scrollToBottom];
        [[AppDelegate shareDelegate]sendMessage:itemM];
        
    } else {
        [SVProgressHUD showErrorWithStatus:@"录音时间过短"];
    }
}
-(void)bofang:(BaseButton *)btn{
    [btn.imageView startAnimating];
    TCMessage *model = btn.model;
    [AudioMsgPlayer playWithURL:model.bodyVoice.voiceUrl delegate:self];
    
}
-(void)audioMsgPlayerDidFinishPlaying:(AudioMsgPlayer*)sender {
    //播放结束时执行的动作
    TCDemoLog(@"audioMsgPlayerDidFinishPlaying");
    
}
#pragma mark 拍照发送通知
-(void)pzsend:(UIImage *)imgGet{
    //UIImage *imgGet = [UIImage imageWithData:not.object];
    imgGet = [UIImage rotateImage:imgGet];
    
    UIImage* imgL = [imgGet resizeImageGreaterThan:1024];
    NSData* dataL = UIImageJPEGRepresentation(imgL, 0.4);
    NSString * pathL = [NSString stringWithFormat:@"%@/tmp/IMG%.0f.jpg", NSHomeDirectory(), [NSDate timeIntervalSinceReferenceDate] * 1000];
    [dataL writeToFile:pathL atomically:YES];
    
    UIImage* imgS = [imgL resizeImageGreaterThan:200];
    NSData* dataS = UIImageJPEGRepresentation(imgS, 0.4);
    NSString * pathS = [NSString stringWithFormat:@"%@/tmp/IMG%.0f.jpg", NSHomeDirectory(), [NSDate timeIntervalSinceReferenceDate] * 1000];
    [dataS writeToFile:pathS atomically:YES];
    
    TCMessage* itemM = [self newMessage];
    itemM.body = [[TCImageMessageBody alloc] init];
    itemM.typeFile = forFileImage;
    itemM.bodyImage.imgUrlL = pathL;
    itemM.bodyImage.imgUrlS = pathS;
    itemM.bodyImage.imgWidth = imgS.size.width;
    itemM.bodyImage.imgHeight = imgS.size.height;
    NSData* data = [NSData dataWithContentsOfFile:itemM.bodyImage.imgUrlL];
    
    [resultArray addObject:itemM];
    
    [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self scrollToBottom];
    
    [[AppDelegate shareDelegate]sendMessage:itemM];
    
}
#pragma mark 视频发送通知
-(void)psend:(NSURL *)url{
    /*
    NSString* tmpName = [NSString stringWithFormat:@"VID%.0f",[NSDate timeIntervalSinceReferenceDate] * 1000];
    NSURL *uploadURL = [NSURL fileURLWithPath:[[NSTemporaryDirectory() stringByAppendingPathComponent:tmpName] stringByAppendingString:@".mp4"]];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVAssetExportSession *avSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    
    avSession.outputFileType  = AVFileTypeMPEG4;
    avSession.outputURL       = uploadURL;
    __weak id wself = self;
    [avSession exportAsynchronouslyWithCompletionHandler:^{
        if (avSession.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"output Video URL %@",uploadURL);
            [wself performSelectorOnMainThread:@selector(updateVideoFileUrl:) withObject:uploadURL waitUntilDone:YES];
        } else {
            [wself performSelectorOnMainThread:@selector(updateVideoFileUrl:) withObject:nil waitUntilDone:YES];
        }
    }];
    */
    
    
    
    //NSURL *url = not.object;
    
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    CMTime audioDuration = asset.duration;
    float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
    TCMessage* itemM = [self newMessage];
    itemM.body = [[TCVideoMessageBody alloc] init];
    itemM.typeFile = forFileVideo;
    itemM.bodyVideo.videoTime = audioDurationSeconds;
    
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
//    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
//    {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetPassthrough];
        NSString *filename = [NSString stringWithFormat:@"%ud",arc4random()%100];
        NSString *exportPath = [NSString stringWithFormat:@"%@/%@.mp4",
                                [NSHomeDirectory() stringByAppendingString:@"/tmp"],
                                filename];
        exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                    NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                    break;
                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"Export canceled");
                    break;
                case AVAssetExportSessionStatusCompleted:
                    NSLog(@"转换成功");
                    NSLog(@"%@", exportPath);
                    break;
                default:
                    break;
            }
        }];
        itemM.bodyVideo.videoUrl = exportPath;
        [resultArray addObject:itemM];
        [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        [self scrollToBottom];
        [[AppDelegate shareDelegate]sendMessage:itemM];
//        [_table reloadData];
//    }
    
    
}

- (void)updateVideoFileUrl:(NSURL*)uploadURL {
    if (uploadURL == nil) {
        NSLog(@"文件读取错误");
    }else{
        AVAsset *asset = [AVURLAsset URLAssetWithURL:uploadURL options:nil];
        CMTime audioDuration = asset.duration;
        float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
        TCMessage* itemM = [self newMessage];
        TCVideoMessageBody *body = [[TCVideoMessageBody alloc] init];
        // body.videoUrl = [uploadURL absoluteString];
       // body.videoTime = audioDurationSeconds;
        itemM.body = body;
        itemM.typeFile = forFileVideo;
        
        
        itemM.bodyVideo.videoTime = audioDurationSeconds;
        itemM.bodyVideo.videoUrl = [uploadURL absoluteString];
        [resultArray addObject:itemM];
        if (resultArray.count>1) {
            
            [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
        [self scrollToBottom];
        [[AppDelegate shareDelegate]sendMessage:itemM];
        //[_table reloadData];
    }
}
#pragma  mark 群详情
- (IBAction)GroupDetailsAction:(UIButton *)sender {
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    GroupDetails*searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupDetails"];
    
    if (_tcs) {  //xhw2018-1-26加备注:如果是从消息列表进到群聊天界面就会有tcs,如果是添加会话选人进群进到群聊天界面就会有model;
        searchResultDetailController.session = _tcs;
    }else{
        TCSession *session = [[TCSession alloc]init];
        session.ID = _model.ID;
        searchResultDetailController.session = session;
    }
    NSLog(@"xhw->GroupChatVC->GroupDetailsAction->groupDetail.session.id:%@",searchResultDetailController.session.ID);
    searchResultDetailController.deletegae = self;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
-(void)upname:(NSString *)name{
    self.navigationItem.title = name;
}

-(UIImagePickerController *)picker{
    if (!_picker) {
        _picker = [[UIImagePickerController alloc]init];
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        _picker.delegate = self;
        
    }
    return _picker;
}

- (void)didGetImage:(UIImage *)image {
    [self pzsend:image];
}

- (void)didGetVideoWithUrl:(NSURL *)videoLocalPathUrl videoData:(NSData *)videoData {
    [self psend:videoLocalPathUrl];
}




@end

